import { acceptHMRUpdate, defineStore } from 'pinia';
import { default as router } from '@/router';
const SET_AVIC_APPS = 'SET_AVIC_APPS';
const SET_APP_STORAGE = 'SET_APP_STORAGE';
const SET_MAP_ROUTER = 'SET_MAP_ROUTER';
// eslint-disable-next-line camelcase
const SET_MICRO_MENU = 'SET_MICRO_MENU';
const GENERATE_ROUTES_DYNAMIC = 'GENERATE_ROUTES_DYNAMIC';
const UPDATE_SKIN = 'UPDATE_SKIN';
import { useUserStore, UserInfo, GLOBAL_USER_CUSTOMED_CONFIG } from '@/store/user';
import { useAppStore, colorMap } from '@/store/app';
import { generatorMicroRouter } from '@/router/generator-routers';

export interface wujieStore {
  AVIC_APPS: string | Array<string>;
  permissions: any;
  componentMapRouter: any;
  appStorage: object;
}
/** 子应用模式使用该文件
 *  缓存子应用注册过的路由映射关系 和 子应用页签打开信息、菜单信息
 * */
export const useWujieStore = defineStore('wujie', {
  state: (): wujieStore => ({
    AVIC_APPS: [],
    permissions: null, // 菜单信息
    componentMapRouter: {}, // 组件路径与路由的映射关系
    appStorage: {}
  }),
  actions: {
    [SET_AVIC_APPS](avicApps: Array<string>) {
      this.AVIC_APPS = avicApps;
    },
    [SET_APP_STORAGE](appStorage: Array<string>) {
      this.appStorage = appStorage;
    },
    [SET_MAP_ROUTER](componentMap) {
      this.componentMapRouter = componentMap;
    },
    // eslint-disable-next-line camelcase
    [SET_MICRO_MENU](permissions) {
      this.permissions = permissions;
    },
    // 初始化子应用token，用户和 权限信息,并构建前端路由
    [GENERATE_ROUTES_DYNAMIC](data) {
      const userStore = useUserStore();
      userStore.SET_TOKEN(data.token);
      // 统一vue2 和 vue3 的用户信息格式
      const { realname, currentAppId, currentOrgId } = data.userInfo;
      const userinfo: UserInfo = { ...data.userInfo, name: realname, appId: currentAppId, orgId: currentOrgId };
      userStore.SET_USER_INFO(userinfo);
      userStore.SET_PERMISSION(data.permissions);
      const userPermissions = generatorMicroRouter(data.permissions);
      const { rootRouters, routes } = userPermissions;
      // 添加到路由表
      rootRouters.forEach((rootRouter) => {
        router.addRoute(rootRouter);
      });
      userStore.SET_ROUTERS(routes);
      // 加载皮肤颜色
      userStore.GET_USER_CUSTOMED_CONFIG(GLOBAL_USER_CUSTOMED_CONFIG).then((gloabalUserConfig) => {
        if (gloabalUserConfig?.G_SKIN_COLOR) {
          const appStore = useAppStore();
          appStore.primaryColor = colorMap[gloabalUserConfig.G_SKIN_COLOR] || gloabalUserConfig.G_SKIN_COLOR;
        }
      });
    },
    [UPDATE_SKIN](color) {
      // 加载皮肤颜色
      const appStore = useAppStore();
      appStore.primaryColor = colorMap[color];
    }
  }
});

const hot = import.meta.webpackHot || (import.meta as any).hot;
if (hot) {
  hot.accept(acceptHMRUpdate(useWujieStore, hot));
}
